<?php
final class TagsManager
{
    public function __construct()
    {
        throw new Exception('獨體模式');
    }
    private static $instances = array();
    public static function instance($table_col)
    {
        if ( ! isset(self::$instances[$table_col]))
        {
            $m = null;
            if (preg_match('/^(\w+)\.(\w+)$/', $table_col, $m))
            {
                self::$instances[$table_col] = new TagsCtrl($m[1], $m[2]);
            }
            else
            {
                throw new Exception('必須設定　資料表.欄位名');
            }
        }
        return self::$instances[$table_col];
    }
    public static function parse($mixed)
    {
        $m = null;
        preg_match_all('/([^,]+)/', join(',',(array)$mixed), $m);
        return $m[1];
    }
}
final class TagsCtrl
{
    private $table_name;
    private $col_name;
    public function __construct($table_name, $col_name)
    {
        $this->table_name = $table_name;
        $this->col_name = $col_name;
    }
    public function fetch()
    {
        $retval = array();
        db_PDO::eachRow(function($row) use(&$retval){
            $retval[] = $row['name'];
        }, db_PDO::query(db_PDO::getConn(), "SELECT {$this->col_name} FROM {$this->table_name}"));
        return $retval;
    }
    public function add($tags)
    {
        $values = array();
        foreach (TagsManager::parse($tags) as $tag)
        {
            $values[] = "('{$tag}')";
        }
        $str_values = join(',', $values);
        $sql = "
            INSERT INTO {$this->table_name} ({$this->col_name}) VALUES {$str_values}
            ON DUPLICATE KEY UPDATE {$this->col_name}={$this->col_name}
      ";
        db_PDO::query(db_PDO::getConn(), $sql);
    }
    public function del($tag)
    {
        if ($tag)
        {
            $sql = "DELETE FROM {$this->table_name} WHERE {$this->col_name}='{$tag}'";
            db_PDO::query(db_PDO::getConn(), $sql);
        }
    }
}
